package com.jack006.article.controller;

import com.jack006.article.vo.Stu;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;

/**
 * @Classname FreemarkerController
 * @Description 页面静态化控制类
 * @Date 2021-07-22 08:33
 * @Created by jack
 */
@Controller
@RequestMapping("free")
public class FreemarkerController {

    @Value("${freemarker.html.target}")
    private String htmlTarget;

    @GetMapping("createHtml")
    @ResponseBody
    public String createHtml(Model model) throws IOException, TemplateException {

        // 0.配置 freemarker 基本环境
        Configuration cfg = new Configuration(Configuration.getVersion());
        // 声明 freemarker 模板所需要加载的目录的位置
        String classPath = this.getClass().getResource("/").getPath();
        cfg.setDirectoryForTemplateLoading(new File(classPath+"templates"));

//        System.out.println(htmlTarget);
//        System.out.println(classPath+"templates");

        // 1. 获得现有的模板 ftl 文件
        Template template = cfg.getTemplate("stu.ftl","utf-8");

        // 2. 获得动态数据
        model.addAttribute("there","jack006.com");
        model = makeModel(model);

        // 3.融合动态数据 ftl, 生成 html
        File tempDic = new File(htmlTarget);
        if (!tempDic.exists()) {
            tempDic.mkdirs();
        }

        Writer out = new FileWriter(htmlTarget+File.separator+"10001.html");
        template.process(model,out);
        out.close();

        return "ok";
    }

    @GetMapping("/hello")
    public String hello(Model model){

        // 定义输出到模板的内容
        model.addAttribute("there","jack006.com");

        makeModel(model);
        // 返回的 stu 是 freemarker 模板的目录
        return "stu";
    }

    private Model makeModel(Model model) {
        Stu stu = new Stu();
        stu.setName("jack006");
        stu.setAge(18);
        stu.setCreateTime(new Date());
        stu.setHaveMarry(true);

        model.addAttribute("stu",stu);

        return model;
    }

}
